package com.saibo.spider.utils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

/**
 * 
 * @author zhangzhening
 *
 */
public class HttpRequestUtil {
	private static RequestConfig requestConfig = null;

	static {
		requestConfig = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000)
				.setConnectionRequestTimeout(10000).build();
	}

	/**
	 * 通用Get请求方法
	 * 
	 * @param url
	 * @param requestHeader
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static CloseableHttpResponse getRequestMethod(String url, Map<String, String> requestHeader){
		return getRequestMethod(url, requestHeader,0);
	}
	
	public static CloseableHttpResponse getRequestMethod(String url, Map<String, String> requestHeader,int num){
		if(num>=3) return null;
		CloseableHttpResponse httpResponse = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpGet httpget = new HttpGet(url);
			httpget.setConfig(requestConfig);// 请求配置，设置超时
			if (null != requestHeader && requestHeader.keySet().size() > 0) {
				// 开始设置请求头参数
				for (String mapkey : requestHeader.keySet()) {
					httpget.setHeader(mapkey, requestHeader.get(mapkey));
				}
			}
			httpResponse = httpclient.execute(httpget);
		} catch (Exception e) {
			//再次请求
			num = num+1;
			System.out.println(num+"次请求："+url+ "  Info: 请求超时"+e);
			getRequestMethod(url, requestHeader,num);
		}
		return httpResponse;
	}

	/**
	 * 通用POST请求方法
	 * 
	 * @param url
	 *            请求地址
	 * @param requestHeader
	 *            请求头
	 * @param requestParam
	 *            请求参数
	 * @return
	 */
	public static CloseableHttpResponse postRequestMethod(String url, Map<String, String> requestHeader,
			Map<String, String> requestParam) {
		CloseableHttpResponse httpResponse = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost(url);
		httppost.setConfig(requestConfig);// 请求配置，设置超时
		if (null != requestHeader && requestHeader.keySet().size() > 0) {
			// 开始设置请求头参数
			for (String mapkey : requestHeader.keySet()) {
				httppost.setHeader(mapkey, requestHeader.get(mapkey));
			}
		}

		List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 存放请求参数
		if (null != requestParam) {
			for (String mapkey : requestParam.keySet()) {
				formParams.add(new BasicNameValuePair(mapkey, requestParam.get(mapkey))); // 设置Post表单参数
			}
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8); // 设置提交参数编码
		httppost.setEntity(entity);
		try {
			httpResponse = httpclient.execute(httppost);
			return httpResponse;
		} catch (IOException e) {
			System.out.println("POST请求提交失败");
			return null;
		}
	}
	
	

	/**
	 * Get请求方法 获取重定向地址
	 * 
	 * @param url
	 * @param requestHeader
	 * @return
	 */
	/**
	 * 获取重定向地址
	 * 
	 * @param path
	 * @return
	 * @throws IOException
	 * @throws MalformedURLException
	 * @throws Exception
	 */
	public static String getRedirectUrl(String path, Map<String, String> requestHeader) {
		if (!path.startsWith("http")) {
			path = "http://weixin.sogou.com" + path;
		}
		System.out.println(path);
		HttpURLConnection conn;
		try {
			conn = (HttpURLConnection) new URL(path).openConnection();
			if (null != requestHeader) {
				for (String string : requestHeader.keySet()) {
					conn.setRequestProperty(string, requestHeader.get(string));
				}
			}
			conn.setInstanceFollowRedirects(false);
			conn.setConnectTimeout(5000);
			return conn.getHeaderField("Location");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * @param args
	 * @throws UnknownHostException 
	 * @throws SocketException 
	 */
	public static void main(String[] args) throws UnknownHostException, SocketException {
		// TODO Auto-generated method stub
		
		//得到IP，输出PC-201309011313/122.206.73.83
		InetAddress ia = InetAddress.getLocalHost();
		System.out.println(ia);
		getLocalMac(ia);
	}
	public static String getLocalMac(InetAddress ia) throws SocketException {
		// TODO Auto-generated method stub
		//获取网卡，获取地址
		byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
		System.out.println("mac数组长度："+mac.length);
		StringBuffer sb = new StringBuffer("");
		for(int i=0; i<mac.length; i++) {
			if(i!=0) {
				sb.append("-");
			}
			//字节转换为整数
			int temp = mac[i]&0xff;
			String str = Integer.toHexString(temp);
			if(str.length()==1) {
				sb.append("0"+str);
			}else {
				sb.append(str);
			}
		}
		return sb.toString().toUpperCase();
	}
}
